<?php

namespace Zlf\Sms\Drive;

use Zlf\AppException\Exception\AppException;
use Zlf\Sms\SmsInterface;
use Zlf\Unit\Str;

abstract class SmsBasics implements SmsInterface
{
    private $configCallable;

    public function setConfigCallable(callable $callable)
    {
        $this->configCallable = $callable;
    }

    protected function getConfig()
    {
        $configCallable = $this->configCallable;
        return $configCallable(static::class);
    }


    /**
     * 获取短信模板内容
     * @param array $template
     * @param string $template_key
     * @return string
     */
    protected function getTemplateContent(array $template, string $template_key): string
    {
        foreach ($template as $item) {
            if ($item['KEY'] === $template_key) {
                return $item['CONTENT'];
            }
        }
        return '';
    }


    /**
     * 生成短信内容
     * @param array $template
     * @param string $template_id
     * @param array $data
     * @return string
     */
    public function renderContent(array $template, string $template_id, array $data = []): string
    {
        $content = $this->getTemplateContent($template, $template_id);
        if (count($data) === 0) return $content;
        return Str::render($content, $data);
    }

    /**
     * 获取短信模板ID
     * @param string $template_key
     * @param array $template
     * @return mixed
     * @throws AppException
     */
    protected function getTemplateId(string $template_key, array $template): string
    {
        foreach ($template as $item) {
            if ($item['KEY'] === $template_key) {
                return $item['TEMPLATE_ID'];
            }
        }
        throw new AppException("无效的短信模板");
    }
}